#! /usr/bin/python

import sys, os, glob, datetime, fileinput

name_server_01 = "8.8.8.8"
name_server_02 = "4.2.2.2"
domain_name = "linux_admin_framework_change_me.com"

#############################################################################
###                      Machine Build Functions                          ###
#############################################################################
def main():
    config_network()
    print "Build complete. Now ...."
    print "1 - Reboot machine (shutdown -r now) to activate new hostname and persist any mac address changes"

pass



def config_network():
    arch_globed_files("/etc/network/interfaces","y")
    add_unique_entry_to_file("/etc/network/interfaces","iface","iface eth0 inet static")
    add_unique_entry_to_file("/etc/network/interfaces","address","address "+sys.argv[2]+"."+sys.argv[3])
    add_unique_entry_to_file("/etc/network/interfaces","netmask","netmask 255.255.255.0")
    add_unique_entry_to_file("/etc/network/interfaces","gateway","gateway "+sys.argv[2]+".1")
    add_unique_entry_to_file("/etc/network/interfaces","dns-nameservers", "dns-nameservers "+name_server_01+" "+name_server_02)
    
    
    #reinitialize hosthame (remove old file)
    arch_globed_files("/etc/hostname","n")
    os.system("touch /etc/hostname")
    add_to_file("/etc/hostname", sys.argv[1]+"."+domain_name)
    
    
    #backup and then edit /etc/hosts
    # could also use echo -e "`ifconfig eth0 | grep 'inet addr:' | cut -d: -f2| cut -d' ' -f1` \t`hostname -s`\t`hostname`" >> /etc/hosts
    arch_globed_files("/etc/hosts","y")
    add_unique_entry_to_file("/etc/hosts","linux_admin_framework","\n#Set by linux-admin-framework.\n")
    add_unique_entry_to_file("/etc/hosts","127.0.0.1","127.0.0.1\t"+"localhost")
    add_unique_entry_to_file("/etc/hosts","127.0.1.1","127.0.1.1\t"+sys.argv[1]+"\t"+sys.argv[1]+"."+domain_name)
    
    #add DNS
    arch_globed_files("/etc/resolv.conf","y")
    
    os.system("/etc/init.d/networking restart")
pass

#############################################################################
###                      Helper Functions                                 ###
#############################################################################
# archive all files fitting a glob
# if preserve is set to "n" destroy the original. 
def arch_globed_files(glb, preserve):
    now = datetime.datetime.now()
    #create the archive destination if it does not yet exist.
    try:
        os.makedirs("/etc/configuration_file_archive")
    #ignore exception thrown if directory exists
    except :        
        pass
        
    filelist=glob.glob(glb)
    for x_file in filelist:
        new_location = "/etc/configuration_file_archive/"+os.path.basename(x_file)+"_"+now.strftime("%Y-%m-%d-%I%M%S%p")        
        if preserve == "n":
            print "archiving -> ", x_file," to ->", new_location 
            os.system("mv "+x_file+" "+new_location)
        else:
            print "backing up -> ", x_file," to ->", new_location 
            os.system("cp "+x_file+" "+new_location)
        


#replace all lines containing the phrase searchExp with the complete new line specified in replaceExp.
#Delete the line if replaceExp is blank 
def replace_any_line_containing_word(x_file,search_exp,replace_exp):
    for line in fileinput.input(x_file, inplace=1):
        if search_exp in line:            
            if replace_exp:                #we don't even want a blank line if null 
                print replace_exp
        else :
            sys.stdout.write(line)

#wrapper function to delete line containing subtraction in it
def remove_from_file(x_file, search_exp):
    replace_any_line_containing_word(x_file,search_exp,"")

#make sure to remove any old occurrences of line and add it to end of file. 
def add_to_file(x_file, replace_exp):
    remove_from_file(x_file, replace_exp)
    file_handle = open(x_file, "a")
    try:
        file_handle.write(replace_exp+"\n")
    finally:
        file_handle.close()    

# add a parameter to a file making sure any old occurrences of the parameter are replaced. 
def add_unique_entry_to_file(x_file,search_exp,replace_exp):
    remove_from_file(x_file, search_exp)
    add_to_file(x_file,replace_exp)

# replace only the characters specified in serach_exp in all places in a file
def replace_all_occurances_of_a_phrase(x_file,search_exp,replace_exp):    
    for line in fileinput.input(x_file, inplace=1):
        line = line.replace(search_exp,replace_exp)        
        sys.stdout.write(line)    # using write instead of print, squelches carriage returns

#############################################################################
###                      Start Here                                       ###
#############################################################################
if __name__ == '__main__':
    if(len(sys.argv) == 4) :
        if os.geteuid() != 0:
            exit("You need to have root privileges to run this script.\nPlease try again, this time using 'sudo'. Exiting.")
        main()        
    else :
        print "Usage: "+sys.argv[0]+" hostname ipaddress_suffix ipaddress_postfix"
        sys.exit()
    pass

pass

